package com.grf.sse.controller;

import cn.hutool.core.collection.ListUtil;
import com.grf.sse.service.SseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @description: 消息推送控制类
 * @author: guorf
 * @date: 2024/8/7
 */
@Slf4j
@CrossOrigin
@RestController
@RequiredArgsConstructor
@RequestMapping("/sse")
public class SseController {

    private final SseService sseService;

    /**
     * @description: 测试消息实时推送
     * @author: guorf
     * @date: 2024/8/7
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter test(){
        return sseService.test();
    }

    /**
     * @description: 建立连接
     * @author: guorf
     * @date: 2024/8/7
     */
    @GetMapping(value = "/connect/{userId}")
    public SseEmitter connect(@PathVariable String userId){
        return sseService.connect(userId);
    }

    /**
     * @description: 发送消息
     * @author: guorf
     * @date: 2024/8/7
     */
    @GetMapping(value = "/send/{userId}/{message}")
    public void sendMessage(@PathVariable String userId, @PathVariable String message){
        sseService.sendMessage(userId, message);
    }

    /**
     * @description: 群发消息
     * @author: guorf
     * @date: 2024/8/7
     */
    @GetMapping(value = "/batch/send/{message}")
    public void batchSendMessage(@PathVariable String message){
        sseService.batchSendMessage(message);
    }

    /**
     * @description: 群发消息
     * @author: guorf
     * @date: 2024/8/7
     */
    @GetMapping(value = "/batch/send/{userIds}/{message}")
    public void batchSendMessage(@PathVariable String userIds, @PathVariable String message){
        sseService.batchSendMessage(ListUtil.of(userIds.split(",")), message);
    }

    /**
     * @description: 关闭连接
     * @author: guorf
     * @date: 2024/8/7
     */
    @GetMapping(value = "/close/{userId}")
    public void closeConnect(@PathVariable String userId){
        sseService.closeConnect(userId);
    }
}
